package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmAddDataService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.service.dynamic.help.DynamicHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.saas.domain.entity.ContactSubDataEntity;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContactSubDataModel;
import com.xbongbong.saas.service.ContactService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 * @date 2021/1/4 15:41
 * @since
 * @version
 */
@Service("contactFormDataServiceImpl")
public class ContactFormDataServiceImpl extends AbstractCrmAddDataService {

    private static final Logger LOG = LoggerFactory.getLogger(ContactFormDataServiceImpl.class);

    @Resource
    private ContactModel contactModel;
    @Resource
    private ContactService contactService;
    @Resource
    private DynamicHelp dynamicHelp;
    @Resource
    private ContactSubDataModel contactSubDataModel;

    @Override
    public List<Integer> businessList() {
        return Arrays.asList(XbbRefTypeEnum.CONTACT.getCode());
    }

    @Override
    public SaveVO save(FormDataAddDTO formDataSaveDTO, BeforeSaveVO beforeSaveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        Integer saasMark = formDataSaveDTO.getSaasMark();
        Integer businessType = formDataSaveDTO.getBusinessType();
        String corpid = formDataSaveDTO.getCorpid();
        Long dataId = 0L;

        try {
            UserVO userVO = new UserVO();
            Integer noApprovalRequired = beforeSaveVO.getNoApprovalRequired() ;
            if (Objects.equals(1, noApprovalRequired)) {
                ContactEntityExt contactEntityExt = new ContactEntityExt();
                FormDataUtil.removeSystemData(paasFormDataEntity.getData());
                Object richTextData = removeRichText(paasFormDataEntity.getData());
                BeanUtil.copyProperties(paasFormDataEntity, contactEntityExt);
                contactModel.insert(contactEntityExt);
                dataId = contactEntityExt.getId();
                // 设置属性用于返回
                setPartialAttributes(dataId, contactEntityExt.getSubFormData(), contactEntityExt.getData(), contactEntityExt.getAddTime(),
                        contactEntityExt.getUpdateTime(), paasFormDataEntity, beforeSaveVO);
                userVO = getUserName(formDataSaveDTO, paasFormDataEntity);
                //文件柜数据保存
                saveFile(formDataSaveDTO, paasFormDataEntity, userVO);
                //富文本数据保存
                saveRichText(formDataSaveDTO, paasFormDataEntity, richTextData);
            }
            return new SaveVO(noApprovalRequired, paasFormDataEntity, dataId, userVO);
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        }
    }

    @Override
    public void saveRollBack(Long id, String corpid, Integer saasMark, Integer businessType) throws XbbException {
        if (id == null || id == 0 || corpid == null || saasMark == null) {
            return ;
        }
        IndexTypeEnum indexTypeEnum = getIndexTypeEnum(corpid, saasMark, businessType);
        //删除主表es数据
        physicalDeleteFormData(id, corpid, indexTypeEnum);
        // 子表单的删除
        List<ContactSubDataEntity> contactSubDataEntities = contactSubDataModel.getByDataId(id, corpid);
        if (!contactSubDataEntities.isEmpty()) {
            physicalDeleteSubBatch(corpid, contactSubDataEntities, IndexTypeEnum.IDX_SAAS_CONTACT_SUB);
        }
    }

    @Override
    public FormDataAddVO afterSave(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        ReRollBackEntity reRollBackEntity = new ReRollBackEntity();

        try {
            Integer noApprovalRequired = saveVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
                packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());
                contactService.afterSave(saasFormSaveDTO);
                // 记录日志
                afterSaveLog(formDataAddDTO, paasFormEntity, paasFormDataEntity, saveVO, beforeSaveVO);
                // 动态处理
                dynamicHelp.addLinkData(saasFormSaveDTO);
                // api
                apiHook(formDataAddDTO, saveVO, beforeSaveVO);
                // 业务规则
                activeRule(formDataAddDTO, beforeSaveVO, paasFormDataEntity, beforeSaveVO.getPaasFormEntityExt());

                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                formDataAddVO.setDataId(paasFormDataEntity.getId());
            }else {
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            }
            formDataAddVO.setFormDataId(paasFormDataEntity.getId());
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            afterSaveRollBack(paasFormDataEntity, dataId, corpid, saasMark, businessType, reRollBackEntity);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            afterSaveRollBack(paasFormDataEntity, dataId, corpid, saasMark, businessType, reRollBackEntity);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
        return formDataAddVO;
    }


    @Override
    public void apiHook(FormDataAddDTO formDataAddDTO, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {
        lowCodeExecuteService(formDataAddDTO, saveVO, beforeSaveVO);
    }

    @Override
    public SaveVO saveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        String corpid = formDataAddDTO.getCorpid();
        Long dataId = 0L;

        try {
            UserVO userVO = new UserVO();
            Integer noApprovalRequired = beforeSaveVO.getNoApprovalRequired() ;
            ContactEntityExt contactEntityExt = new ContactEntityExt();
            Object richTextData = removeRichText(paasFormDataEntity.getData());
            JSONObject originData = (JSONObject) paasFormDataEntity.getData().clone();

            FormDataUtil.removeSystemData(paasFormDataEntity.getData());
            BeanUtil.copyProperties(paasFormDataEntity, contactEntityExt);
            contactModel.insert(contactEntityExt);
            dataId = contactEntityExt.getId();
            // 设置属性用于返回
            setPartialAttributes(dataId, contactEntityExt.getSubFormData(), contactEntityExt.getData(), contactEntityExt.getAddTime(),
                    contactEntityExt.getUpdateTime(), paasFormDataEntity, beforeSaveVO);
            userVO = getUserName(formDataAddDTO, paasFormDataEntity);
            //文件柜数据保存
//            saveFile(formDataAddDTO, paasFormDataEntity, userVO);
            //富文本数据保存
            saveRichText(formDataAddDTO, paasFormDataEntity, richTextData);
            paasFormDataEntity.setData(originData);
            return new SaveVO(noApprovalRequired, paasFormDataEntity, dataId, userVO);
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        }
    }

    @Override
    public FormDataAddVO afterSaveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        ReRollBackEntity reRollBackEntity = new ReRollBackEntity();

        try {
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
            packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
            saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());
            contactService.afterSaveForWorkflow(saasFormSaveDTO);
            // 记录日志
//            afterSaveLog(formDataAddDTO, paasFormDataEntity, saveVO, beforeSaveVO);
            // api
//            apiHook(formDataAddDTO, saveVO, beforeSaveVO);
            // 业务规则
//            activeRule(formDataAddDTO, beforeSaveVO, paasFormDataEntity, beforeSaveVO.getPaasFormEntityExt());

            formDataAddVO.setDataId(paasFormDataEntity.getId());
            formDataAddVO.setFormDataId(paasFormDataEntity.getId());
            formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
        } catch (Exception e) {
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            afterSaveRollBack(paasFormDataEntity, dataId, corpid, saasMark, businessType, reRollBackEntity);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
        return formDataAddVO;
    }

    @Override
    public void afterSaveRollBack(PaasFormDataEntity newPaasFormDataEntity, Long dataId, String corpid, Integer saasMark, Integer businessType, ReRollBackEntity reRollBackEntity) throws XbbException {
        try {
            saveRollBack(dataId, corpid, saasMark, businessType);

        } catch (Exception e) {
            LOG.error("abstractFormDataServiceImpl.afterSaveRollBack 回滚失败：", e);
        }

    }
}
